package com.example.blog.common.validation;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.springframework.beans.BeanWrapperImpl;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

public class DateRangeValidator implements ConstraintValidator<DateRange, Object> {
    private String startDateField;
    private String endDateField;
    private int maxDays;

    @Override
    public void initialize(DateRange constraintAnnotation) {
        this.startDateField = constraintAnnotation.startDateField();
        this.endDateField = constraintAnnotation.endDateField();
        this.maxDays = constraintAnnotation.maxDays();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null) {
            return true;
        }

        BeanWrapperImpl wrapper = new BeanWrapperImpl(value);
        LocalDate startDate = (LocalDate) wrapper.getPropertyValue(startDateField);
        LocalDate endDate = (LocalDate) wrapper.getPropertyValue(endDateField);

        if (startDate == null || endDate == null) {
            return false;
        }

        // 检查开始日期是否在结束日期之前
        if (startDate.isAfter(endDate)) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("开始日期必须在结束日期之前")
                .addPropertyNode(startDateField)
                .addConstraintViolation();
            return false;
        }

        // 检查日期范围是否超过最大天数
        long daysBetween = ChronoUnit.DAYS.between(startDate, endDate);
        if (daysBetween > maxDays) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("日期范围不能超过" + maxDays + "天")
                .addPropertyNode(endDateField)
                .addConstraintViolation();
            return false;
        }

        // 检查是否选择了未来日期
        LocalDate today = LocalDate.now();
        if (startDate.isAfter(today) || endDate.isAfter(today)) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("不能选择未来日期")
                .addPropertyNode(endDate.isAfter(today) ? endDateField : startDateField)
                .addConstraintViolation();
            return false;
        }

        return true;
    }
} 